<template>
  <div class="wrap-container">
      <el-card class="main-card" shadow="never">
        <template #header>
          <div class="card-header">
            <h1>
              <el-icon><DocumentChecked /></el-icon>
              采购订单
            </h1>
            <div class="header-actions">
              <el-button type="primary" @click="openAddOrder">
                <el-icon><Plus /></el-icon>
                新增采购订单
              </el-button>
            </div>
          </div>
        </template>

        <!-- 搜索过滤区域 -->
        <div class="filter-section">
          <el-form :model="searchForm" label-width="80px">
            <el-row :gutter="5">
              <el-col :span="4">
                <el-form-item label="采购单号">
                  <el-input v-model="searchForm.code" placeholder="请输入订单号" clearable/>
                </el-form-item>
              </el-col>

              <el-col :span="4">
                <el-form-item label="归属日期">
                  <el-date-picker
                      v-model="searchForm.order_date"
                      type="date"
                      placeholder="归属日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="7">
                <el-form-item label="创建日期">
                  <el-date-picker
                      type="daterange"
                      v-model="rangeDate"
                      start-placeholder="开始日期"
                      range-separator="至"
                      end-placeholder="结束日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="3">
                <el-form-item label="状态">
                  <el-select v-model="searchForm.status" placeholder="请选择状态">
<!--                    订单状态：1-待确认, 2-取消  3-已确认, 4-配送中  5-部分入库, 6-已完成入库, 0-已作废（软删除）-->
                    <el-option label="全部" value="" />
                    <el-option label="待确认" :value="1" />
                    <el-option label="已取消" :value="2" />
                    <el-option label="已确认" :value="3" />
                    <el-option label="配送中" :value="4" />
                    <el-option label="部分入库" :value="5" />
                    <el-option label="已完成" :value="6" />
                    <el-option label="已作废" :value="0" />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="3">
                <el-form-item label="紧急程度">
                  <el-select v-model="searchForm.urgency_level" placeholder="请选择紧急程度" style="width: 100%">
                    <el-option label="全部" value="" />
                    <el-option label="普通" value="1" />
                    <el-option label="紧急" value="2" />
                    <el-option label="非常紧急" value="3" />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="3">
                <el-form-item label="创建人">
                  <el-select v-model="searchForm.created_uid" placeholder="请选择供创建人" style="width: 100%">
                    <el-option label="全部" value="" />
<!--                    <el-option label="张三" value="1" />-->
<!--                    <el-option label="李四" value="2" />-->
<!--                    <el-option label="王五" value="3" />-->
                    <el-option :label="v.user_name"
                                   :value="v.user_id"
                                   v-for="(v,k) in usersList"
                                   :key="'usr_'+k"/>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="食材名称">
                  <el-input v-model="searchForm.goodsName" placeholder="请输入食材名称" clearable/>
                </el-form-item>
              </el-col>

              <el-col :span="5">
                <el-form-item label="供应商">
                  <el-select v-model="searchForm.supplierId" placeholder="请选择供应商" style="width: 100%">
                    <el-option label="全部" value="" />
<!--                    <el-option label="绿源有机蔬菜供应公司" value="1" />-->
<!--                    <el-option label="优质肉类供应中心" value="2" />-->
<!--                    <el-option label="海鲜水产直供商" value="3" />-->
                        <el-option :label="v.supplier_name"
                                   :value="v.supplier_id"
                                   v-for="(v,k) in suppliersList"
                                   :key="'spl_'+k"/>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <div class="form-actions">
                  <el-button @click="resetForm">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                  <el-button type="primary" @click="searchOrders">
                    <el-icon><Search /></el-icon>
                    查询
                  </el-button>
                </div>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <!-- 数据表格区域 -->
        <div class="data-table-section">
          <el-table :data="tableData" style="width: 100%" v-loading="loading">
            <el-table-column type="index" label="序号"  align="center" width="90"/>
<!--            <el-table-column prop="order_id" label="订单ID"  width="100"/>-->
            <el-table-column prop="title" label="采购单名称"  width="200" show-overflow-tooltip/>
            <el-table-column prop="order_code" label="采购单号"  width="160" align="center"/>
            <el-table-column prop="order_date" label="归属日期" width="120" :formatter="formateDate"/>
            <el-table-column prop="goods_count" label="总数量" width="80" align="center"/>
            <el-table-column prop="total_amount" label="总金额"  align="center" :formatter="formateMoney"/>

            <el-table-column prop="status" label="状态" width="80" align="center">
<!--              订单状态：1-待确认, 2-取消  3-已确认, 4-配送中  5-部分入库, 6-已完成入库, 0-已作废（软删除）-->
              <template #default="scope">
                <el-tag v-if="scope.row.status === 1" type="warning">待确认</el-tag>
                <el-tag v-else-if="scope.row.status === 2" type="warning">已取消</el-tag>
                <el-tag v-else-if="scope.row.status === 3" type="primary">已确认</el-tag>
                <el-tag v-else-if="scope.row.status === 4" type="info">配送中</el-tag>
                <el-tag v-else-if="scope.row.status === 5" type="danger">部分入库</el-tag>
                <el-tag v-else-if="scope.row.status === 6" type="success">已完成</el-tag>
                <el-tag v-else-if="scope.row.status === 0" type="danger">已作废</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="创建时间"  width="180" :formatter="formateDateTime"/>
            <el-table-column prop="order_notes" label="备注"  show-overflow-tooltip width="160"/>
            <el-table-column label="操作" width="230" fixed="right" align="right">
              <template #default="scope">
                <el-button size="large" type="primary" link @click="openViewOrder(scope.row)">
                  <el-icon><View /></el-icon>
                  查看
                </el-button>

                <el-button
                    v-if="scope.row.status === 1 || scope.row.status === 2"
                    size="large"
                    type="info"
                    link
                    @click="openEditOrder(scope.row)"
                >
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>

                <el-button
                    v-if="scope.row.status == 1"
                    size="large"
                    type="danger"
                    link
                    @click="cancelOrder(scope.row)"
                >
                  <el-icon><Close /></el-icon>
                  取消订单
                </el-button>

                <el-button
                    v-if="scope.row.status == 1"
                    size="large"
                    type="success"
                    link
                    @click="confirmOrder(scope.row)"
                >
                  <el-icon><Stamp /></el-icon>
                  确认订单
                </el-button>

                <el-button
                    v-if="scope.row.status == 3"
                    size="large"
                    type="warning"
                    link
                    @click="readyDelivery(scope.row)"
                >
                  <el-icon><Van /></el-icon>
                  准备发货
                </el-button>
                <el-button
                    v-if="scope.row.status == 4"
                    size="small"
                    type="primary"
                    link
                    @click="goToInventory(scope.row.order_code)"
                >
                  <el-icon><Upload /></el-icon>
                  入库
                </el-button>
                <el-button
                    v-if="scope.row.status == 4"
                    size="large"
                    type="danger"
                    link
                    @click="partInStorage(scope.row)"
                >
                  <el-icon><InfoFilled /></el-icon>
                  部分入库
                </el-button>

                <el-button
                    v-if="scope.row.status == 4"
                    size="large"
                    type="success"
                    link
                    @click="receiveOrder(scope.row)"
                >
                  <el-icon><SuccessFilled /></el-icon>
                  全部入库
                </el-button>

                <el-button
                    v-if="scope.row.status == 1 || scope.row.status == 2"
                    size="large"
                    type="danger"
                    link
                    @click="deleteOrderRow(scope.row.order_id)"
                >
                  <el-icon><Delete /></el-icon>
                  删除订单
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页组件 -->
          <div class="pagination-container">
            <el-pagination
                v-model:current-page="pagination.currentPage"
                v-model:page-size="pagination.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="pagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </el-card>
  </div>

  <!-- 订单详情抽屉 -->
  <el-drawer
      v-model="drawerVisible"
      direction="rtl"
      size="78%"
      @close="closeDrawer"
      class="custom-drawer"
      :header-style="{ marginBottom: '20px' }"
  >
    <template #header>
      <div class="custom-header">
        <h4>{{ drawerTitle }} {{ drawerTitle!="新增采购订单" ? " - "+currentOrder.orderNo :"" }}</h4>
      </div>
    </template>

    <div class="drawer-content">
      <!-- 订单汇总信息 -->
      <div class="section-title">订单汇总信息</div>
      <el-form :model="currentOrder" label-width="80px" :disabled="isViewMode" ref="AddOrderFormRef"  :rules="rules">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="采购名称" prop="title">
              <el-input v-model="currentOrder.title" placeholder="请输入采购单" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="归档日期" prop="orderDate">
              <el-date-picker
                v-model="currentOrder.orderDate"
                type="date"
                placeholder="请选择归档日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="申请人" prop="createdUid">
              <el-select v-model="currentOrder.createdUid" placeholder="请选择申请人" style="width: 100%">
<!--                <el-option label="张三" value="张三" />-->
<!--                <el-option label="李四" value="李四" />-->
<!--                <el-option label="王五" value="王五" />-->
                <el-option v-for="(user,index) in usersList" :key="'usr2_'+index" :label="user.user_name" :value="user.user_id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="紧急程度" prop="urgencyLevel">
              <el-select v-model="currentOrder.urgencyLevel" placeholder="请选择紧急程度" style="width: 100%">
                <el-option label="普通" :value="1" />
                <el-option label="紧急" :value="2" />
                <el-option label="非常紧急" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="供应商" prop="suppliers">
              <el-checkbox-group v-model="currentOrder.suppliers" @change="handleSupplyChange()" :disabled="isEditMode">
<!--                <el-checkbox label="绿源有机蔬菜供应公司" />-->
<!--                <el-checkbox label="优质肉类供应中心" />-->
<!--                <el-checkbox label="海鲜水产直供商" />-->
                <el-checkbox v-for="(supplier,index) in suppliersList"
                             :key="'spl2_'+index"
                             :label="supplier.supplier_name"
                             :value="supplier.supplier_id"
                />
              </el-checkbox-group>
<!--              {{currentOrder.suppliers}}-->
            </el-form-item>
          </el-col>
        </el-row>

      <!-- 订单明细 -->
      <div class="section-title">订单明细</div>
      <div class="table-header" v-if="!isViewMode">
        <div class="summary-info-inline">
          <span class="summary-item">商品总数: <strong>{{ totalItems }}</strong></span>
          <span class="summary-item">合计金额: <strong>¥{{ totalAmount }}</strong></span>
        </div>
        <div>
          <el-button type="danger" size="small" @click="resetItem" v-if="!isViewMode" :disabled="isEditMode" v-show="currentOrder.items.length>0">
            <i class="fas fa-plus"></i>
            清空商品
          </el-button>
<!--          <el-button type="primary" size="small" @click="addItem" v-if="!isViewMode" :disabled="isEditMode">-->
<!--            <i class="fas fa-plus"></i>-->
<!--            添加商品-->
<!--          </el-button>-->
          <el-button type="primary" size="small" @click="addOrderFoodOpen" v-if="isEditMode">
            <i class="fas fa-plus"></i>
            选择食材
          </el-button>
        </div>
      </div>

      <el-table :data="currentOrder.items" style="width: 100%" :show-header="true" align="center" fit>
        <el-table-column type="index" label="#"  />
        <el-table-column prop="goods_name" label="物品名称" show-overflow-tooltip width="130">
          <template #default="scope">
            <span style="font-weight: bold">{{ scope.row.goods_name }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="cate_name" label="分类" >
          <template #default="scope" v-if="!isViewMode">
           {{ scope.row.cate_name }}
          </template>
          <template #default="scope" v-else>
            {{ scope.row.cate_name }}
          </template>
        </el-table-column>

        <el-table-column prop="specification" label="规格型号">
          <template #default="scope">
            {{ scope.row.specification }}
          </template>
        </el-table-column>

        <el-table-column prop="unit" label="单位" width="70">
          <template #default="scope">
            {{ scope.row.unit }}
          </template>
        </el-table-column>

        <el-table-column prop="in_price" label="入库价" align="center" width="160">
          <template #default="scope" v-if="!isViewMode">
<!--            <el-input v-model="scope.row.in_price" size="default"/>-->
            <el-input-number v-model="scope.row.in_price" :precision="2" :step="1" :min="1" style="width: 130px;" size="small"
                             @change="handleGoodsChange(scope.row.goods_id,scope.row)"/>
          </template>
          <template #default="scope" v-else>
            <span style="color: #409eff;font-weight: bold">￥{{ scope.row.in_price }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="out_price" label="出库价" align="center" width="100">
          <template #default="scope" v-if="!isViewMode">
            <el-input v-model="scope.row.out_price" size="default" type="number"  @change="handleGoodsChange(scope.row.goods_id,scope.row)"/>
          </template>
          <template #default="scope" v-else>
            <span style="color: #409eff;">￥{{ scope.row.out_price}}</span>
          </template>
        </el-table-column>

        <el-table-column prop="safety_stock" label="安全库存" align="center" width="100" >
          <template #default="scope" v-if="!isViewMode">
            <el-input v-model="scope.row.safety_stock" size="default" type="number" @change="handleGoodsChange(scope.row.goods_id,scope.row)"/>
          </template>
          <template #default="scope" v-else>
            <span style="color: #c12727;font-weight: bold">{{ scope.row.safety_stock }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="quantity" label="采购数量" align="center" width="160">
          <template #default="scope" v-if="!isViewMode">
<!--            <el-input v-model="scope.row.quantity" type="number" />-->
            <el-input-number v-model="scope.row.quantity" :precision="1" :step="1" :min="1" style="width: 130px;" size="small"/>
          </template>
          <template #default="scope" v-else>
            <span style="color:orangered;font-weight: 900">{{ scope.row.quantity }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="amount" label="总价" align="center" width="95">
          <template #default="scope">
            <span style="color: #ff6600;font-weight: bold">￥{{ (scope.row.in_price * scope.row.quantity).toFixed(2) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="supplier_name" label="供应商" width="135" align="center" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.supplier_name }}
          </template>
        </el-table-column>

        <el-table-column prop="supplier_name" label="备注"  align="left" width="150" >
          <template #default="scope" v-if="!isViewMode">
            <el-input v-model="scope.row.notes" style="width:120px" size="default"/>
          </template>
          <template #default="scope" v-else show-overflow-tooltip>
            {{ scope.row.notes }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="80" v-if="!isViewMode" align="center">
          <template #default="scope">
            <el-button size="small" type="primary" link @click="removeAddItem(scope.$index)" v-if="!isEditMode">
              <el-icon><Delete /></el-icon>删除
            </el-button>
            <el-button size="small" type="primary" link @click="removeItem(scope.$index, scope.row.goods_id)" v-if="isEditMode">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 统计信息 -->
      <div class="summary-info" v-if="isViewMode">
        <div class="summary-item">
          商品总数: <strong>{{ totalItems }}</strong>
        </div>
        <div class="summary-item">
          合计金额: <strong>¥{{ totalAmount }}</strong>
        </div>
      </div>

      <!-- 备注 -->
      <div style="margin-top: 20px;">
        <el-form-item label="备注" prop="notes">
          <el-input
              v-model="currentOrder.notes"
              type="textarea"
              :readonly="isViewMode"
              placeholder="请输入备注信息"
              :rows="5"
              :cols="20"
          />
        </el-form-item>
      </div>
      </el-form>
    </div>

    <template #footer>
      <div style="flex: auto">
        <el-button @click="closeDrawer">取消</el-button>
        <el-button v-if="isViewMode" type="primary" @click="closeDrawer">返回</el-button>
        <el-button v-if="!isViewMode" type="primary" @click="saveOrder(AddOrderFormRef)">保存</el-button>
      </div>
    </template>

  </el-drawer>

<!-- 采购单 商品列表 -->
  <el-dialog
      v-model="dialogVisible"
      title="选择新食材"
      width="32%"
      :before-close="handleClose"
      class="addOrderItem"
  >
    <el-form :model="foodsForm" label-width="auto" style="max-width: 600px" ref="addFoodForm" :rules="addFoodFormRules">
      <el-form-item label="食材名称" prop="goods_name">
        <el-select
            v-model="foodsForm.goods_id"
            filterable
            remote
            placeholder="请输入食材名称"
            :remote-method="remoteMethod"
            :loading="foodsSelectLoading"
            @change="handleFoodsChange"
            @clear="handleFoodsClear"
            clearable
        >
          <el-option
              v-for="item in foodsSelectOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="数量" prop="quantity">
        <el-input-number v-model="foodsForm.quantity" :precision="1" :step="1" :min="1" class="quantity"/>
      </el-form-item>

      <el-form-item label="单价">
        <el-input-number v-model="foodsForm.in_price"  :min="0.00" class="in_price" :precision="2" @change="handleGoodsChange(foodsForm.goods_id,foodsForm)"/>
      </el-form-item>

      <el-form-item label="出库价">
        <el-input-number v-model="foodsForm.out_price"  :min="0.00" :precision="2" :step="1" class="out_price" @change="handleGoodsChange(foodsForm.goods_id,foodsForm)"/>
      </el-form-item>

      <el-form-item label="合计金额">
        <el-input :value="foodsForm.in_price * foodsForm.quantity" class="total_price" type="number" min="0.00" disabled="disabled" />
      </el-form-item>

      <el-form-item label="分类">
        <el-input v-model="foodsForm.cate_name" disabled="disabled"/>
      </el-form-item>

      <el-form-item label="规格">
        <el-input v-model="foodsForm.specification" disabled="disabled"/>
      </el-form-item>

      <el-form-item label="单位">
        <el-input v-model="foodsForm.unit" disabled="disabled"/>
      </el-form-item>

      <el-form-item label="供应商">
        <el-input v-model="foodsForm.supplier_name" disabled="disabled"/>
      </el-form-item>

      <el-form-item label="安全库存">
        <el-input-number v-model="foodsForm.safety_stock" class="safety_stock" :min="1" :precision="1" :step="1" @change="handleGoodsChange(foodsForm.goods_id,foodsForm)"/>
      </el-form-item>

      <el-form-item label="食材备注">
        <el-input v-model="foodsForm.notes" placeholder="食材的说明信息，可选填"/>
      </el-form-item>

    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAddOrderFood(addFoodForm)">
          确 定
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// 导入Element Plus图标
import {
  Plus,
  Search,
  Refresh,
  View,
  Edit,
  Van,
  Delete,
  DocumentChecked,
  Close,
  SuccessFilled,
  InfoFilled,
  Stamp
} from '@element-plus/icons-vue'
// 导入dayjs
import dayjs from "dayjs";
// 导入订单服务
import {
  getOrdersList,
  getSupplierMaterials,
  createOrder,
  updateOrder,
  updateOrderStatus,
  createMaterial,
  deleteMaterial,
  deleteOrder,
  updateMaterials
} from '../../api/orders'
// 供应商列表
import {getSuppliersList} from "../../api/suppliers.js"
// 用户列表
import {getUserInfo} from "../../api/user.js"
// 当前登录的用户信息
import {useAuthStore} from "../../stores/userStore.js"
// 导入商品列表方法
import {getGoodsList} from "../../api/goods.js"
// 获取路由实例
import { useRoute, useRouter } from 'vue-router';
const router = useRouter()

// 获取供应商列表
let suppliersList = ref([])
const getSuppliersListItem = async () => {
  try {
    const res = await getSuppliersList();
    if (res.code === 0 && res.data) {
      suppliersList.value = res.data.data.map((item) => ({
        supplier_id: item.supplier_id,
        supplier_name: item.supplier_name
      }))
    }
  } catch(err){
    console.log("获取供应商列表失败", err)
  }
}
getSuppliersListItem()

// 获取用户列表
let usersList = ref([])
const getUsersItems =async ()=>{
  try {
    const res = await getUserInfo();
    // console.log("获取用户列表成功", res)
    if (res.code === 0 && res.data) {
      usersList.value = res.data.map((item) => ({
        user_id: item.user_id,
        user_name: item.user_name
      }))
    }
  } catch(err){
    console.log("获取用户列表失败",err)
  }
}
getUsersItems()

// 获取pinia中存放的 用户信息
// {
//   user_name: "",
//   user_id: null,
//   role_id: null, //角色id
//   token: null,   // token 也需要持久化
// }
const userStore = useAuthStore()
const userInfo = computed(()=>{
  return userStore.user;
})
console.log("当前登录的用户信息:",userInfo,userInfo.value.user_id)
// 用户id
const userId = computed(()=>{
  return userInfo.value.user_id;
})
console.log("当前登录的用户ID:",userId.value)

// 根据供应商 获取该供应商的 食材列表
const handleSupplyChange = async ()=>{
  // console.log("新增采购单,选择的供应商id:",currentOrder.suppliers)
  try{
    if(currentOrder.suppliers.length==0){
      currentOrder.items=[];//清空列表
      return ElMessage.warning('请至少勾选供1个应商，以此获取采购食材信息!')
    }

    let data = {
      "supplierId":JSON.stringify(currentOrder.suppliers), //字符串格式的数组
      "pageSize":100
    }
    const result = await getSupplierMaterials(data)
    let list = result?.data?.list || [];
    let goods_info = list.map(item=>{
      item.goods_name = item.name;//后端返回的名称，避免冲突，修改成goods_name
      item.in_price = Number(item.in_price)
      return item;
      // return {
      //   // A 显示的 列表 对应的字段
      //   "goods_id": item.goods_id,
      //   "code": item.code,
      //   "goods_name": item.name, //后端返回的名称，避免冲突，修改成goods_name
      //   "goods_pic": item.goods_pic,
      //   "cate_id": item.cate_id,
      //   "specification": item.specification,
      //   "unit": item.unit,
      //   "supplier_id": item.supplier_id,
      //   "status": item.status,
      //   "in_price": Number(item.in_price),
      //   "out_price": Number(item.out_price),
      //   "safety_stock": Number(item.safety_stock),
      // }
    })
    //显示列表
    currentOrder.items = goods_info
    console.log("获取供应商的物资列表",result)
  }catch (err){
    console.log("获取供应商的物资列表失败",err)
  }
}
// 搜索表单数据
const searchForm = reactive({
  code: '',
  order_date: '',
  // rangeDate:[],
  status: '',
  urgency_level: '',
  created_uid: '',
  supplierId: '',
  goodsName:''
})
let rangeDate = ref("") //订单日期

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 12
})

// 加载状态
const loading = ref(false)

// 抽屉可见性
const drawerVisible = ref(false)

// 抽屉标题
const drawerTitle = ref('')

// 是否为查看模式
const isViewMode = ref(false)

// 是否为编辑模式
const isEditMode = ref(false)

// 采购单位列表数据
const tableData = ref([
  // {
  //   id: 1,
  //   orderNo: 'PO20230815001',
  //   supplier: '绿源有机蔬菜供应公司',
  //   itemName: '西红柿',
  //   spec: '一级',
  //   unit: '斤',
  //   price: '¥3.50',
  //   quantity: '50',
  //   amount: '¥175.00',
  //   status: 'pending'
  // },
])

// 采购单商品数据
const currDate = dayjs().format('YYYY-MM-DD'); //当前日期
const currentOrder = reactive({
  title:"", //
  createdUid: userId.value, // 创建采购单ID，默认当前登录的用户id
  notes: '',     // 备注
  orderNo: '',   //编辑、查看采购单编号：PO20230815001，新增的时候不需要填，值设置为空
  suppliers: [], // 供应商列表，新增的时候必填，需要转为字符串（join()或JSON.stringify()）
  orderDate: currDate, // 订单归档日期
  urgencyLevel: 1,   //紧急度
  items: [
    // {
    //   "goods_id": 1,
    //   "code": "G001001",
    //   "name": "东北大米",
    //   "goods_pic": null,
    //   "cate_id": 1,
    //   "specification": "5kg/袋",
    //   "unit": "袋",
    //   "supplier_id": 1,
    //   "status": 1,
    //   "in_price": "45.00",
    //   "out_price": "50.00",
    //   "safety_stock": "50.0",
    //   "note": "食堂常备主食",
    //   "created_at": "2025-11-13T09:46:39.000Z",
    //   "updated_at": "2025-11-13T09:47:29.000Z",
    //   "cate_name": "主食",
    //   "supplier_name": "京北绿色农场",
    //   "current_stock": "286.5",
    //   "stock_alert_min": "0.3",
    //   "stock_alert_max": "1.5",
    //   "quantity":1
    // },
    // {
    //   "goods_id": 2,
    //   "code": "G001002",
    //   "name": "挂面",
    //   "goods_pic": null,
    //   "cate_id": 1,
    //   "specification": "500g/包",
    //   "unit": "包",
    //   "supplier_id": 1,
    //   "status": 1,
    //   "in_price": "5.50",
    //   "out_price": "7.00",
    //   "safety_stock": "30.0",
    //   "note": "快速面食",
    //   "created_at": "2025-11-13T09:46:39.000Z",
    //   "updated_at": "2025-11-13T09:47:30.000Z",
    //   "cate_name": "主食",
    //   "supplier_name": "京北绿色农场",
    //   "current_stock": "100.0",
    //   "stock_alert_min": "0.3",
    //   "stock_alert_max": "1.5",
    //   "quantity":1
    // },
  ]
})
// 新增食材表单
const foodsForm = reactive({
  "goods_name": "",
  "goodsId":0,
  "supplierId": "",
  "orderedCount": 0.0, // 数量
  "unitPrice": 0.00,   // 单价(入库单价)
  "unit":"",
  "notes":"",
  "spec":"",
  "out_price": 0.00,
  "safety_stock":0.0
})

// 采购订单列表方法
const getOrders = async () => {
  console.log("获取采购订单列表数据",rangeDate.value)
  try {
    loading.value = true;
    let formData = {
      // 搜索参数
      code:searchForm.code,
      order_date: searchForm.order_date,
      startDate:rangeDate.value[0],
      endDate:rangeDate.value[1],
      status: searchForm.status,
      urgency_level: searchForm.urgency_level,
      created_uid: searchForm.created_uid,
      goodsName: searchForm.goodsName,
      supplierId: searchForm.supplierId,
      // 分页参数
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    }
    // console.log(formData)
    let result = await getOrdersList(formData)
    // console.log(result)

    tableData.value = result.data.list||[];
    pagination.total = result.data.pagination.total||0;
    pagination.pageSize = result.data.pagination.pageSize;
    pagination.currentPage = result.data.pagination.page

    loading.value = false;
  } catch (error) {
    loading.value = false;
    ElMessage.error(error.msg)
  }
}
getOrders()

// 定义方法，格式化日期
const formateDate = (row, column, cellValue, index) => {
  return dayjs(cellValue).format('YYYY-MM-DD')
}
// 格式化日期+时间
const formateDateTime = (row, column, cellValue, index) => {
  return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
}
// 格式化金额
const formateMoney = (row, column, cellValue, index)=>{
  return '¥' + Number(cellValue).toFixed(2)
}

// 重置搜索表单
const resetForm = () => {
  // 重置表单数据
  searchForm.code = '';
  searchForm.order_date = '';
  searchForm.status = '';
  searchForm.urgency_level = '';
  searchForm.created_uid = userId.value;
  searchForm.supplierId = '';
  searchForm.goodsName = "";

  rangeDate.value=""
  // 重新获取列表数据
  getOrders();
}

// 搜索
const searchOrders = () => {
  console.log('执行查询操作');
  getOrders();
  // ElMessage.info('执行查询操作');
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  console.log(`每页条数: ${val}`)
  getOrders();
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  console.log(`当前页: ${val}`)
  getOrders()
}

// 手动新增一个商品
const addItem = () => {
  currentOrder.items.push({
    // A 显示的 列表 对应的字段
    "goods_id": 3,
    // "code": "G002001",
    "goods_name": "大白菜",
    // "goods_pic": null,
    // "cate_id": 2,
    "specification": "散装",
    "unit": "斤",
    // "supplier_id": 1,
    // "status": 1,
    "in_price": "1.20",
    // "out_price": "1.80",
    // "safety_stock": "100.0",
    "note": "北方常备",
    // "created_at": "2025-11-13T09:46:39.000Z",
    // "updated_at": "2025-11-13T09:47:31.000Z",
    "cate_name": "蔬菜",
    "supplier_name": "京北绿色农场",
    // "current_stock": "50.0",
    // "stock_alert_min": "0.3",
    // "stock_alert_max": "1.5",
    "quantity":1

    //B 新增采购单时的数据
    // "goodsId":item.goods_id,
    // "supplierId": item.supplier_id,
    // "orderedCount": item.quantity?Number(item.quantity):0.00, // 数量
    // "unitPrice": item.in_price? Number(item.in_price):0.00,   // 单价(入库单价)
    // "unit":item.unit,
    // "notes": item.note,
    // "spec":item.specification

    //C 编辑 采购单时的数据（同新增）
    // "goodsId":item.goods_id,
    // "supplierId": item.supplierId,//供应商id
    // "orderedCount": item.quantity?Number(item.quantity):0.00, // 数量
    // "unitPrice": item.in_price? Number(item.in_price):0.00,   // 单价(入库单价)
    // "unit":item.unit,                          //单位
    // "notes": item.notes,                       //备注
    // "spec":item.specification

    // D 新增商品项目时 的API返回的字段(待处理：30-4-采购订单-新增采购单中的商品项)
    // "item_id": 94,
    // "order_id": 45,
    // "goods_id": 2,
    // "goods_name": "挂面",
    // "spec": "500g/包",
    // "unit": "包",
    // "unit_price": "5.50",
    // "ordered_count": 2,
    // "amount": 11,
    // "notes": "备注信息",
    // "supplier_id": 1,
    // "supplier_name": "京北绿色农场",
    // "cate_name": "主食"
    // B、C 都是基于A，综合D也要按 B或C方式push，就可以在AB 中直接使用了
  })
}

//清空物品列表
const resetItem = ()=>{
  currentOrder.items =[]
  currentOrder.suppliers = []
}

// 添加时：删除采购单列表中 的物品的
const removeAddItem = (index) => {
  currentOrder.items.splice(index, 1)
}

// 编辑时：删除采购单列表中 的物品
const removeItem = (index,goods_id) => {
  if(!goods_id){
    ElMessage.error('请选择要删除的食材');
    return;
  }

  ElMessageBox.confirm(
    `确定要从采购单中删除这条食材吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async ()=>{
    // 调用api删除数据库中的数据
    console.log("准备删除数据:",currentOrder.order_id,goods_id)
    try {
      let result = await deleteMaterial(currentOrder.order_id,goods_id)
      if(result.code === 0){
        // 删除页面中的数据
        currentOrder.items.splice(index, 1)
        getOrders(); //刷新列表数据
        ElMessage.success('删除成功');
      }
    } catch (err){
      console.log(err)
      ElMessage.error('删除失败');
    }
  })
  .catch((e)=>{
    return;
  })
}

// 计算总金额
const totalAmount = computed(() => {
  return currentOrder.items.reduce((total, item) => {
    return total + (item.in_price * item.quantity)
  }, 0).toFixed(2)
})

// 计算商品总数
const totalItems = computed(() => {
  return currentOrder.items.reduce((total, item) => {
    return total + parseInt(item.quantity) || 0
  }, 0)
})

// 新增采购单 打开抽屉
const openAddOrder = () => {
  drawerTitle.value = '新增采购订单';
  isViewMode.value = false;
  isEditMode.value = false; //关闭编辑模式
  // 重置当前订单数据-先注释。
  Object.assign(currentOrder, {
    orderNo: '',
    title: '',
    orderDate: '',
    urgencyLevel: 1,
    createdUid: 1,
    suppliers: [],//用户选择的供应商id数组
    notes: '',
    items: [
      // {
      //   itemName: '',
      //   category: '',
      //   spec: '',
      //   unit: 0.00,
      //   in_price: 0,
      //   quantity: 0.00,
      //   amount: 0.00,
      //   supplier: ''
      // },
    ]
  })
  drawerVisible.value = true
}

// 新增采购单 表单验证
const AddOrderFormRef = ref(null)
const rules = {
  title: [
    { required: true, message: '请输入采购单标题', trigger: 'blur' }
  ],
  orderDate: [
    { required: true, message: '请选择订单归档日期', trigger: 'change' }
  ],
  createdUid: [
    { required: true, message: '请选择创建人', trigger: 'change' }
  ],
  suppliers: [
    { required: true, message: '请选择供应商', trigger: 'change' }
  ],
  urgencyLevel: [
    { required: true, message: '请选择紧急度', trigger: 'change' }
  ],
  notes:[
      { required: true, message: '请填写采购单备注', trigger: 'blur' }
  ]
}

// 新增、编辑采购单 提交
const saveOrder = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    // 验证表单是否通过
    if (!valid) {
      ElMessage.error('请填完整填写表单项!')
      console.log('error submit!', fields)
      return;
    }
    // 组装订单数据
    if(currentOrder.items.length==0){
      return ElMessage.warning('请选择供应商和商品！到少要添加一件商品才能创建采购订单!')
    }

    // 新增
    if (!currentOrder.orderNo) {
      // 1.组装 食材明细数据，准备添加
      let details = currentOrder.items.map(item => {
        return {
          "goods_name":item.goods_name,//新加,保存到订单明细中
          "goodsId":item.goods_id,
          "supplierId": item.supplier_id,
          "orderedCount": item.quantity?Number(item.quantity):0.00, // 数量
          "unitPrice": item.in_price? Number(item.in_price):0.00,   // 单价(入库单价)
          "unit":item.unit,
          "notes": item.notes,
          "spec":item.specification,
          "cate_id":item.cate_id,//新加,保存到订单明细中
          "out_price":item.out_price?Number(item.out_price):0.00,//新加,保存到订单明细中
          "safety_stock":item.safety_stock?Number(item.safety_stock):0.0//新加,保存到订单明细中
        }
      })

      // 2.整体数据
      let formData = {
        "createdUid": currentOrder.createdUid, //申请人id
        "notes": currentOrder.notes,
        "orderDate":currentOrder.orderDate, //归档日期
        "title":currentOrder.title, //采购订单名称
        "urgencyLevel":currentOrder.urgencyLevel,         //紧急程序
        "status":1,//默认状态：待确认
        "details":details
      }

      // currentOrder.supplier = currentOrder.suppliers.join(', ');
      try {
        console.log("保存的订单数据（原始）:",currentOrder,"组装后的数据：",formData)
        Object.assign(formData, {
          "items":JSON.stringify(details)
        })
        let result = await createOrder(formData)
        console.log("处理后的结果:",result)
        ElMessage.success('新增采购单成功!')
        getOrders() //刷新列表
      }catch (err){
        console.log("保存采购单失败",err)
        ElMessage.error('保存采购单失败:'+err.msg)
      }
    }
    else {
        // 编辑
        // 1.组装 食材明细数据，准备添加
        let details = currentOrder.items.map(item => {
          return {
            // 食材列表 页面用的数据
            // goods_id:item.goods_id,       //食材id
            // name: item.goods_name,        //食材名称
            // cate_name: item.cate_name,    //分类名称
            // specification: item.spec,     //规格型号
            // unit: item.unit,              //单位
            // in_price:item.unit_price,     //单价
            // quantity: item.ordered_count, //采购数量
            // // amount: item.amount,       //采购金额：自动计算
            // supplier_name: item.supplier_name  //供应商名称

            "goodsId":item.goods_id,
            "supplierId": item.supplierId,//供应商id
            "orderedCount": item.quantity?Number(item.quantity):0.00, // 数量
            "unitPrice": item.in_price? Number(item.in_price):0.00,   // 单价(入库单价)
            "unit":item.unit,                          //单位
            "notes": item.notes,                       //备注
            "spec":item.specification,                 //规格型号
            "goods_name":item.goods_name,//新加,保存到订单明细中
            "out_price":item.out_price?Number(item.out_price):0.00,//新加,保存到订单明细中
            "cate_id":item.cate_id,//新加,保存到订单明细中
            "safety_stock":item.safety_stock?Number(item.safety_stock):0.0//新加,保存到订单明细中
          }
        })

        // 2.整体数据
        let formData = {
          "updatedUid": userId.value, //更新人id，需要调整
          "notes": currentOrder.notes,           //食材的备注
          "orderDate":currentOrder.orderDate,    //归档日期
          "title":currentOrder.title,            //采购订单名称
          "urgencyLevel":currentOrder.urgencyLevel,  //紧急程序
          "status":1,                            //默认状态：待确认
          "details":details                      //食材列表
        }

        try {
          // Object.assign(formData, {
          //   "details":JSON.stringify(details),
          //   "updatedUid": currentOrder.createdUid,//当前登录的用户id
          // })
          delete formData.items;
          console.log("保存 修改的 订单数据（原始）:",currentOrder,"组装后的数据：",formData)

          let result = await updateOrder(Number(currentOrder.order_id),formData)
          if(result.code==0){
            ElMessage.success('编辑采购单成功!')
            getOrders() //刷新列表
          }else{
            ElMessage.error('编辑采购单失败:'+result.msg)
          }
          isViewMode.value = false
        }catch (err){
          ElMessage.error('保存采购单失败:'+err.msg)
          isViewMode.value = false
        }
        //
    }
    closeDrawer() //关闭抽屉
  })
}

// 查看采购单
const openViewOrder = (row) => {
  drawerTitle.value = '查看采购订单'
  isViewMode.value = true
  // console.log("查看采购单:",row)

  // 设置当前订单数据
  // 组装数据
  //1.采购单 总体数据
  currentOrder.createdUid = row.created_uid; //申请人id
  currentOrder.orderDate=row.order_date; //归档日期
  currentOrder.orderNo = row.order_code; //采购单编号：PO20251118002
  currentOrder.title = row.title; //采购订单名称
  currentOrder.urgencyLevel=row.urgency_level;        //紧急程序
  currentOrder.status=row.status;//默认状态：待确认
  currentOrder.notes=row.order_notes;  //采购单备注
  // currentOrder.items=[];       //采购商品列表
  currentOrder.order_id = row.order_id; //采购单id

  // 2.采购商品列表
  let goodsList= row.details.map(item => {
    return {
      // 食材列表 页面用的数据
      goods_name: item.goods_name,        //食材名称
      cate_name: item.cate_name,    //分类名称
      specification: item.spec,     //规格型号
      unit: item.unit,              //单位
      in_price:item.unit_price,     //单价
      quantity: item.ordered_count, //采购数量
      // amount: item.amount,       //采购金额：自动计算
      supplier_name: item.supplier_name,  //供应商名称
      supplierId: item.supplier_id, //供应商id
      notes: item.item_notes,             //食材的备注
      out_price:item.out_price,     //出库单价 11.27新增3个
      cate_id:item.cate_id,         //分类id
      safety_stock:item.safety_stock //安全库存
    }
  })
  currentOrder.items=goodsList;
  // console.log("查看采购订单，获取当前订单数据:",currentOrder)

  // 3.获取供应商id数组
  let supplierIdsArr = row.details.map(item => item.supplier_id)
  let supplierIds = [...new Set(supplierIdsArr)]
  // console.log("查看采购订单，获取供应商id数组:",supplierIds)
  currentOrder.suppliers = supplierIds //显示供应商名称

  // 4.显示查看抽屉
  drawerVisible.value = true
}

//编辑采购单
const openEditOrder = (row) => {
  console.log("编辑采购单：row:",row)
  drawerTitle.value = '编辑采购订单'
  isViewMode.value = false //可以编辑
  isEditMode.value = true; //编辑模式,禁用 食材列表中的 添加、删除、清空按钮；禁用供应商选择复选框。

  //1.采购单 总体数据
  currentOrder.createdUid = row.created_uid; //申请人id
  currentOrder.orderDate=row.order_date; //归档日期
  currentOrder.orderNo = row.order_code; //采购单编号：PO20251118002
  currentOrder.title = row.title; //采购订单名称
  currentOrder.urgencyLevel=row.urgency_level;        //紧急程序
  currentOrder.status=row.status;//默认状态：待确认
  currentOrder.notes=row.order_notes;  //采购单备注
  // currentOrder.items=[];       //采购商品列表
  currentOrder.order_id = row.order_id; //采购单id
  // 2.采购商品列表
  let goodsList= row.details.map(item => {
    return {
      // 食材列表 页面用的数据
      goods_id:item.goods_id,       //食材id
      goods_name: item.goods_name,  //食材名称
      cate_name: item.cate_name,    //分类名称
      specification: item.spec,     //规格型号
      unit: item.unit,              //单位
      in_price:item.unit_price?Number(item.unit_price):0.00,     //单价
      quantity: item.ordered_count?Number(item.ordered_count):0.0, //采购数量
      // amount: item.amount,       //采购金额：自动计算
      supplier_name: item.supplier_name,  //供应商名称
      supplierId: item.supplier_id, //供应商id
      notes: item.item_notes,       //食材的备注
      out_price:item.out_price?Number(item.out_price).toFixed(2):0.00,     //出库单价 11.27新增3个
      cate_id:item.cate_id,         //分类id
      safety_stock:item.safety_stock?Number(item.safety_stock).toFixed(1):0.0 //安全库存
    }
  })
  currentOrder.items=goodsList;
  // console.log("编辑 采购单，获取当前订单数据:",currentOrder)

  // 3.获取供应商id数组
  let supplierIdsArr = row.details.map(item => item.supplier_id)
  let supplierIds = [...new Set(supplierIdsArr)]
  // console.log("查看采购订单，获取供应商id数组:",supplierIds)
  currentOrder.suppliers = supplierIds //显示供应商名称

  // 4.显示编辑抽屉
  drawerVisible.value = true
}

// 采购单中 商品列表 新增
const dialogVisible = ref(false)    //显示隐藏 添加食材对话框
// 下拉框 数据
const foodsSelectLoading = ref(false) //下拉操作时，显示加载中
const foodsList = ref([])             //从后端到到的原始数据
const foodsSelectOption = ref([])     //select 渲染需要的 数据格式

const addOrderFoodOpen = () => {
  dialogVisible.value = true
  handleFoodsClear(); //清空搜索框结果表单
}

// 添加食材
// 清空搜索框结果
const handleFoodsClear = ()=>{
  foodsForm.goods_id = ""
  foodsForm.goods_name = ""
  foodsForm.cate_name = ""
  foodsForm.specification = ""
  foodsForm.unit = ""
  foodsForm.in_price = 0.00
  foodsForm.quantity = 0.0
  foodsForm.amount = 0.00
  foodsForm.supplier_name = ""
  foodsForm.supplierId = 0
  foodsForm.notes = ""
  foodsForm.out_price = 0.00 //11.27
  foodsForm.cate_id = ""
  foodsForm.safety_stock = 0
}

// 根据关键字搜索食材
const remoteMethod = async (query) => {
  if(query){
    foodsSelectLoading.value = true;
    console.log("搜索食材:",query)
    let result = await getGoodsList({
      keyword: query,
      page: 1,
      pageSize: 30,
      status:1
    })
    console.log("搜索食材结果:",result)
    if(result.code===0){
      foodsList.value = result.data.data
      foodsSelectOption.value = result.data.data.map(item => {
        return {
          value: item.goods_id,
          label: `${item.goods_id} - ${item.name} ( ${item.specification}  - ￥${item.in_price} -  ${item.supplier_name} )`
        }
      })
    }
    foodsSelectLoading.value = false;
  }else{
    foodsList.value = []
    foodsSelectOption.value = []
    foodsSelectLoading.value = false
  }
}

// 处理食物选择结果-显示食材
const handleFoodsChange = async (goods_id)=>{
  console.log("食材选择结果:",goods_id,"原始数据:",foodsList.value)
  //获取这个食材信息：1.从foodsList中获取 2.从服务端获取
  let arr = foodsList.value.find(item => item.goods_id == goods_id)
  let food = arr || []
  console.log("食材信息:",food)
  if(food){
    // 在添加表单中显示
    foodsForm.goods_id = food.goods_id
    foodsForm.goods_name = food.name
    foodsForm.cate_name = food.cate_name
    foodsForm.specification = food.specification
    foodsForm.unit = food.unit
    foodsForm.in_price = food.in_price?Number(food.in_price).toFixed(2):0.00
    foodsForm.quantity = 1 //数量，默认1
    // foodsForm.amount = food.in_price * foodsForm.quantity
    foodsForm.supplier_name = food.supplier_name
    foodsForm.supplierId = food.supplier_id
    foodsForm.notes = food.notes||""
    foodsForm.code = food.code //显示用

    foodsForm.out_price = food.out_price?Number(food.out_price).toFixed(2):0.00;    //出库单价 11.27新增3个
    foodsForm.cate_id=food.cate_id;        //分类id
    foodsForm.safety_stock = food.safety_stock?Number(food.safety_stock).toFixed(1):0.0;//安全库存
  }
}

// 新增食材表单验证
const addFoodForm = ref(); //表单对象

// 自定义验证规则
const checkQuantity = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请输入采购数量！'));
  }
  if (value <= 0) {
    return callback(new Error('采购数量必须大于0！'));
  }
  callback();
}

const addFoodFormRules = reactive({
  goods_name: [
    { required: true, message: '请输入要检索的食材名称！', trigger: 'blur' }
  ],
  quantity: [{ validator: checkQuantity, trigger: 'blur' }],
})

// 保存 新增加的食材
const saveAddOrderFood = async (formEl) => {
  if(!formEl){
    return;
  }
  await formEl.validate()
      .then(async valid => {
        if(valid){
          //
          // 调用api,保存数据
          try {
            let data = {
              goodsId: foodsForm.goods_id,
              goodsCount: foodsForm.quantity,
              notes: foodsForm.notes
            }
            let result = await createMaterial(currentOrder.order_id,data)
            console.log("保存添加食材结果:",result)
            // 添加成功
            if(result.code===0){
              let food = result.data;
              // 添加到列表中
              let trData =  {
                // 表格中显示的数据
                goods_name: food.goods_name,  //商品名称
                cate_name: food.cate_name,    //
                specification: food.spec,     //规格型号
                unit: food.unit,              //单位
                in_price:food.unit_price,     //单价
                quantity: food.ordered_count, //数量
                supplier_name: food.supplier_name,//供应商名称
                notes:food.notes,             //备注
                goods_id:food.goods_id,       //食材id，提交表单时需要
                supplierId: food.supplier_id, //供应商id，提交表单时需要
                out_price:food.out_price,     //出库单价 11.27新增3个
                cate_id:food.cate_id,         //分类id
                safety_stock:food.safety_stock//安全库存
              }
              currentOrder.items.push(trData) //更新列表
              console.log("添加食材到采购单列表的数据:",trData)

              // 更新 供应端id列表
              // currentOrder.suppliers.push(food.supplierId)
              // console.log("更新 采购单的供应商列表1:",currentOrder.suppliers)
              if(!currentOrder.suppliers.includes(food.supplier_id)){
                currentOrder.suppliers.push(food.supplier_id)
              }
              // console.log("更新 采购单的供应商列表2:",currentOrder.suppliers)
            }

            dialogVisible.value = false;  //关闭添加食材对话框
            handleFoodsClear()            //清空添加表单
            getOrders()                   //刷新列表
            ElMessage.success("添加食材到采购单成功!")

          } catch (err){
            console.log("添加食材失败:",err)
          }
        //
        }

    })
      .catch(err => {
        // console.log("验证失败:",err)
        ElMessage.error('请输入食材名称再进行添加!')
      });
}

// 关闭添加食材对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 修改采购订单状态 start
// 修改采购订单的状态:定义一个公共方法，方便修改
// 订单状态：1-待确认, 2-取消  3-已确认, 4-配送中  5-部分入库, 6-已完成入库, 0-已作废（软删除）
/*
* @desc 修改采购订单的状态
* @params orderId 订单id
* @params status 订单状态
* @params notes 备注
* */
const updateOrderState= async (orderId,status,notes) => {
  console.log("修改采购订单的状态:",orderId,status,notes,userId.value)
  try {
    let result = await updateOrderStatus(orderId,{
      status:status,
      operatorId:userId.value,//固定不用传递
      notes:notes
    })
    if(result.code==0){
      ElMessage.success('更新成功!')
      getOrders() //重新加载数据
    }else{
      ElMessage.error('更新失败!')
    }
  }catch(err){
    ElMessage.error(err.msg || '操作失败！')
  }
}

// 取消订单
const cancelOrder = (row) => {
  ElMessageBox.confirm('确认要取消该订单吗？', '取消订单', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // ElMessage.success('订单已取消!')
    console.log("取消订单：row:",row,row.order_id)
    updateOrderState(row.order_id,2,'订单已取消')
  })
}

// 确认订单
const confirmOrder = (row) => {
  ElMessageBox.confirm('确认要确认该订单吗？', '确认订单', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // ElMessage.success('订单已确认!')
    console.log("确认订单：row:",row,row.order_id)
    updateOrderState(row.order_id,3,'订单已确认')
  })
}
// 准备配送
const readyDelivery = (row) => {
  ElMessageBox.confirm('确认要准备配送吗？', '准备配送', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // ElMessage.success('订单已确认!')
    console.log("准备配送：row:",row,row.order_id)
    updateOrderState(row.order_id,4,'订单已确认')
  })
}

// 部分入库
const partInStorage = (row) => {
  ElMessageBox.confirm('确认要部分入库吗？', '部分入库', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // ElMessage.success('订单已确认!')
    console.log("部分入库：row:",row,row.order_id)
    updateOrderState(row.order_id,5,'订单已确认')
  })
}

// 全部入库(完成)
const receiveOrder = (row) => {
  ElMessageBox.confirm('确认全部入库？', '收货确认', {
    confirmButtonText: '确认收货',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    console.log("全部入库：row:",row,row.order_id)
    updateOrderState(row.order_id,6,'订单已确认')
  })
}

// 软删除
const deleteOrderSoft = (row) => {
  ElMessageBox.confirm('确认要把该订单放入回收站吗？', '删除订单', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // ElMessage.success('订单已确认!')
    console.log("删除订单：row:",row,row.order_id)
    updateOrderState(row.order_id,0,'订单已确认')
  })
}

// 删除采购订单（永久）
const deleteOrderRow = (order_id) => {
  ElMessageBox.confirm('确认要永久删除该订单吗？', '删除订单', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      console.log("删除订单：order_id:",order_id)
      let result = await deleteOrder(order_id)
      if (result.code === 0){
        ElMessage.success(`采购单(${result.data.orderId})成功已删除`);
        getOrders(); //重新加载 列表数据
      }
    } catch (err){
      console.log("删除订单失败:",err)
      ElMessage.error(err.msg || '操作失败！')
    }
  })
}
// 修改采购订单状态 end

// 更新食材表信息
const handleGoodsChange = async (goods_id,data) => {
  try {
    let send_data = {
      inPrice:data.in_price?Number(data.in_price):0.00,
      outPrice:data.out_price?Number(data.out_price):0.00,
      safetyStock:data.safety_stock?Number(data.safety_stock):0.0
    }
    console.log("更新食材表信息:",goods_id,send_data)

    let result = await updateMaterials(goods_id,send_data)
    if(result.code==0){
      ElMessage.success('更新成功!')
      getOrders() //重新加载数据
    }else{
      ElMessage.error('更新失败!')
    }
  }catch(err){
    ElMessage.error(err.msg || '操作失败！')
  }
}

// 入库
const goToInventory = (order_code) => {
  console.log('跳转入库管理页面:',order_code)

  router.push({
    name:'inventoryinList',// /inventoryin/list
    query:{
      order_code:order_code
    }
  })
  ElMessage.info('跳转入库管理页面')
}

// 关闭抽屉
const closeDrawer = () => {
  drawerVisible.value = false
}
</script>

<style lang="less" scoped>
.wrap-container {
  width: 100%;
  min-height: 90vh;
  padding: 0;
  background-color: #f5f5f5;
  .main-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h1 {
        font-size: 20px;
        font-weight: 600;
        color: var(--text-primary);
        display: flex;
        align-items: center;
        gap: 8px;
        margin: 0;
        //图标
        .el-icon{
          font-size: 26px;
          font-weight: 600;
        }
      }
    }

    .filter-section {
      margin: 12px 0;

      .form-actions {
        display: flex;
        height: 100%;
      }
    }

    .data-table-section {
      :deep(.el-table) {
        .el-table__header {
          th {
            background-color: #f5f7fa;
          }
        }
      }
      
      .pagination-container {
        margin-top: 18px;
        display: flex;
        justify-content: flex-end;
      }
    }
  }
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--primary-color);
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 1px solid var(--border-color);
}
 
.drawer-content {
  padding: 0;
  height: 100%;
  // overflow-y: auto;

  .section-title {
    margin-top: 5px;
    
    &:first-child {
      margin-top: 0;
    }
  }

  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }

  .summary-info-inline {
    .summary-item {
      margin-right: 20px;
      font-size: 14px;
      
      strong {
        color: #ff6600;
        font-size: 16px;
      }
    }
  }

  .summary-info {
    display: flex;
    justify-content: space-between;
    margin: 15px 0;
    padding: 10px;
    background-color: #f5f5f5;
    border-radius: 4px;

    .summary-item {
      font-size: 14px;
      
      strong {
        color: #ff6600;
        font-size: 16px;
      }
    }
  }

  //数字输入框样式
  :deep(.el-input-number){
    &.is-center{
      .el-input__inner{
        color:red;
        font-size:17px;
        font-weight: bold;
      }
    }
  }
}
</style>
<style lang="less">
 // 自定义抽屉样式
 .custom-drawer{
    .el-drawer__header {
      margin-bottom:0;
      padding: 5px 15px;

      h4{
        margin:10px 0;
        font-size: 20px;
        font-weight: bold;
      }
    }

    .el-drawer__body{
      padding-top: 0;
    }
 }
 // 自定义模态框中的表单样式
 .addOrderItem{
   //数字输入框样式
   //.el-input-number{
   //  &.is-center{
   //    .el-input__inner{
   //      font-size:17px;
   //      font-weight: bold;
   //      color: red;
   //    }
   //  }
   //}
   //数量
   .quantity {
     .el-input {
       .el-input__wrapper {
         .el-input__inner {
           font-size: 18px;
           font-weight: bold;
           color: orangered;
         }
       }
     }
   }

   //单价
   .in_price {
     .el-input {
       .el-input__wrapper {
         .el-input__inner {
           font-size: 17px;
           font-weight: bold;
           color: green;
         }
       }
     }
   }

   //禁用的按钮样式
   .el-input {
     &.is-disabled {
       .el-input__inner {
         -webkit-text-fill-color: orangered;
         font-weight: 700;
         font-size: 15px;
       }
     }
   }

   //合计金额
   .total_price {
     .el-input {
       &.is-disabled {
         .el-input__inner {
           -webkit-text-fill-color: blue;
           font-weight: 700;
           font-size: 20px;
         }
       }
     }
   }

   //合计金额
   //.out_price {
   //  .el-input {
   //    .el-input__wrapper {
   //      .el-input__inner {
   //        font-size: 17px;
   //        //font-weight: bold;
   //        color: blue;
   //      }
   //    }
   //  }
   //}



 }
</style>